package com.shop.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shop.constan.GatewayConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Mono;

import java.time.Duration;

@Configuration
public class RouteConfig {
    @Autowired
    private StringRedisTemplate redisTemplate;

    //路由
    @Bean
    public RouteLocator routeLocator(RouteLocatorBuilder builder) {
        return builder
                .routes()
                .route("auth-server-router", r -> r.path("/oauth/**")
                        .filters(f -> f.modifyResponseBody(String.class, String.class, (exchanges, s) -> {
                            // 1.拿到request  判断登录
                            String path = exchanges.getRequest().getURI().getPath();
                            if (GatewayConstant.LOGIN_PATH.equals(path)) {
                                JSONObject jsonObject = JSON.parseObject(s);
                                //拿到key保存redis
                                String access_token = jsonObject.getString("access_token");
                                if (!StringUtils.isEmpty(access_token)) {
                                    //时间
                                    Long expires_in = jsonObject.getLong("expires_in");
                                    redisTemplate.opsForValue().set(GatewayConstant.JWT_PREFIX + access_token, "" + Duration.ofSeconds(expires_in));
                                }


                            }
                            return Mono.just(s);

                        })).uri("lb://auth-server"))
                .build();
    }

}
